package com.ctim.service.user;

import com.ctim.common.exception.EnumPcsService;
import com.ctim.common.exception.PcsRunTimeException;
import com.ctim.common.pcs.PcsListResult;
import com.ctim.common.tool.json.JSONUtil;
import com.ctim.dao.user.UserDao;
import com.ctim.dao.user.UserRoleDao;
import com.ctim.model.user.User;
import com.ctim.service.bean.UserBean;
import com.ctim.service.config.TransactionalControl;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * User: lb on 2016/8/26.
 * Date:2016-08-26-11:41
 * desc：
 */
@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserRoleDao userRoleDao;


    /**
     * 根据手机号查询用户详情
     *
     * @param phone
     * @return
     */
    public User getUser(String phone) {
        return userDao.selectUserByPhone(phone);
    }


    /**
     * 用户列表
     *
     * @param username
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public PcsListResult getUsers(String username, int pageIndex, int pageSize) {
        PcsListResult pcsListResult = new PcsListResult();
        Integer total;
        List<User> list = new ArrayList<>();
        // 偏移量
        int pageOffset = pageSize * (pageIndex - 1);
        total = userDao.countUser(username);
        if (total != null && total > 0) {
            list = userDao.selectUserByPhone(username, pageOffset, pageSize);
        }
        pcsListResult.setData(JSONUtil.filterDateProperties(list, User.class));
        pcsListResult.setTotal(total);
        return pcsListResult;
    }

    /**
     * 添加用户
     *
     * @param userBean userBean
     */
    @TransactionalControl
    public void createUser(UserBean userBean) {
        User user = new User();
        if (userBean.getEmail()!=null) {
            userBean.setEmail(userBean.getEmail().trim());
        }
        if (userDao.selectUserByPhone(userBean.getPhone()) != null) {
            throw new PcsRunTimeException(EnumPcsService.BUSINESS_PHONE_EXISTED);
        }
        if (StringUtils.isNoneBlank(userBean.getEmail()) && userDao.selectUserByEmail(userBean.getEmail()) != null) {
            throw new PcsRunTimeException(EnumPcsService.BUSINESS_EMAIL_EXISTED);
        }
        BeanUtils.copyProperties(userBean,user);
        userDao.insertUser(user);
        String[] roleIds = userBean.getRoleIds().split(",");
        userRoleDao.insertUserRole(userBean.getUserId(), roleIds);
    }


    /**
     * 修改用户
     *
     * @param userBean
     */
    @TransactionalControl
    public void updateUser(UserBean userBean) {
        User user = new User();
        if (userBean.getEmail()!=null) {
            userBean.setEmail(userBean.getEmail().trim());
        }
        User su = userDao.selectUserByUserId(userBean.getUserId());
        if ((su.getPhone()==null || !su.getPhone().equals(userBean.getPhone())) &&
                userDao.selectUserByPhone(userBean.getPhone()) != null) {
            throw new PcsRunTimeException(EnumPcsService.BUSINESS_PHONE_EXISTED);
        }
        if ((su.getEmail()==null || !su.getEmail().equals(userBean.getEmail())) &&
                userDao.selectUserByEmail(userBean.getEmail()) != null) {
            throw new PcsRunTimeException(EnumPcsService.BUSINESS_EMAIL_EXISTED);
        }
        BeanUtils.copyProperties(userBean,user);
        userDao.updateUser(user);
        if (userBean.getRoleIds() != null){
            String[] roleIds = userBean.getRoleIds().split(",");
            userRoleDao.updateUserRole(userBean.getUserId(), roleIds);
        }

    }

    /**
     * 删除用户     查询此人是否挂了客户，是否是团队成员，如果是则不允许删除
     *
     * @param userId 用户id
     */
    public boolean deleteUser(Integer userId,Integer operateUserId) {
        /*int customerCount = userDao.countUserNum(userId);
        if (customerCount > 0) {
            throw new PcsRunTimeException(EnumPcsService.BUSINESS_USER_HAS_CUSTOMER);
        }*/
        int ret = userDao.deleteUser(userId, operateUserId);
        return ret > 0;
    }

    public Integer editpass(Integer userId, String newPassword) {
        return userDao.alterpassword(userId, newPassword);
    }


}
